import React, { useState, useEffect } from "react";
import Waterfall from "./Waterfall.tsx";

interface ImageItem {
  id: number;
  url: string;
  aspectRatio: number;
}

function TryWaterfall() {
  const [items, setItems] = useState<ImageItem[]>([]);
  const [hasMore, setHasMore] = useState(true);

  // 预加载图片并获取宽高比
  const preloadImage = (url: string): Promise<number> => {
    return new Promise((resolve) => {
      const img = new Image();
      img.src = url;
      img.onload = () => {
        resolve(img.width / img.height);
      };
      img.onerror = () => {
        resolve(1); // 加载失败时使用默认比例
      };
    });
  };

  // 加载初始数据
  const loadInitialData = async () => {
    const newItems = await Promise.all(
      Array.from({ length: 20 }, async (_, i) => {
        const url = `https://picsum.photos/300/${
          200 + Math.floor(Math.random() * 300)
        }`;
        const aspectRatio = await preloadImage(url);
        return {
          id: i,
          url,
          aspectRatio,
        };
      })
    );
    setItems(newItems);
  };

  useEffect(() => {
    loadInitialData();
  }, []);

  const loadMore = async () => {
    const newItems = await Promise.all(
      Array.from({ length: 10 }, async (_, i) => {
        const url = `https://picsum.photos/300/${
          200 + Math.floor(Math.random() * 300)
        }`;
        const aspectRatio = await preloadImage(url);
        return {
          id: items.length + i,
          url,
          aspectRatio,
        };
      })
    );

    setItems((prev) => [...prev, ...newItems]);
    if (items.length > 100) {
      setHasMore(false);
    }
  };

  return (
    <div style={{ padding: "20px" }}>
      <Waterfall
        dataList={items}
        columns={3}
        columnGap={16}
        rowGap={16}
        hasMore={hasMore}
        onLoadMore={loadMore}
        getAspectRatio={(item) => item.aspectRatio}
        renderItem={(item) => (
          <div
            style={{
              backgroundColor: "#f0f0f0",
              borderRadius: "8px",
              overflow: "hidden",
              height: "100%",
              position: "relative",
            }}
          >
            <img
              src={item.url}
              alt={`图片 ${item.id}`}
              style={{
                width: "100%",
                height: "100%",
                objectFit: "cover",
                display: "block",
              }}
            />
          </div>
        )}
      />
    </div>
  );
}

export default TryWaterfall;
